package com.yuncheng.spcyApi.webOffice;

import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.spcyApi.entity.SpcyRsOnlineEdit;
import com.yuncheng.spcyApi.entity.SpcySqsxQywjcl;
import com.yuncheng.spcyApi.entity.SpcySqsxWjjl;
import com.yuncheng.spcyApi.service.ISpcyRsOnlineEditService;
import com.yuncheng.spcyApi.service.ISpcySqsxQywjclService;
import com.yuncheng.spcyApi.service.ISpcySqsxWjjlService;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.spcyApi.utils.HnCaUtils;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.spcyApi.vo.common.HttpResultVo;
import com.yuncheng.spcyApi.vo.common.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import utils.Util;


import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "审评查验-WebOffice在线文档编辑接口")
@RestController
@RequestMapping("/api/spzx-spcy/webOfficeApi")
public class WebOfficeApi {
    private static final Logger log = LoggerFactory.getLogger(WebOfficeApi.class);

    @Resource
    private WebOfficeFile webOfficeFIle;

    @Resource
    private ISpcySqsxWjjlService spcySqsxWjjlService;

    @Resource
    private ISpcyRsOnlineEditService spcyRsOnlineEditService;

    @Resource
    private ISpcySqsxQywjclService spcySqsxQywjclService;

    @Resource
    private HnCaUtils hnCaUtils;

    @Log(title = "申请事项-将在线文档转为Pdf文档并保存")
    @ApiOperation(value = "申请事项-将在线文档转为Pdf文档并保存")
    @ApiImplicitParam(name = "id",value = "文件id")
    @GetMapping(value = "getDocxToPdf")
    public HttpResult<?> getDocxToPdf(@RequestParam(value = "id",defaultValue = "") String id){

        /*if (StringUtils.isBlank(id)){
            return HttpResult.error("文件参数为空！");
        }

        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在！");
        }

        if (StringUtils.isNotBlank(wjjl.getFwjlx()) && wjjl.getFwjlx().equals(".pdf")){
            return HttpResult.error("当前文件已经是pdf无法再次生成，请重新编辑文档");
        }

        // 关闭文档
        Result closeResult1 = webOfficeFIle.closeFile(id);
        if (!closeResult1.isSuccess()){
            return HttpResult.error(closeResult1.getMessage());
        }

        // 将在线文档转pdf
        Result result = webOfficeFIle.getDocxToPdfFile(wjjl, wjjl.getFcflj());
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }*/

        // 关闭文档
        return HttpResult.ok("服务不可用");
    }

    @Log(title = "申请事项-将在线文档转为Pdf文档并保存和盖章")
    @ApiOperation(value = "申请事项-将在线文档转为Pdf文档并保存和盖章")
    @ApiImplicitParam(name = "id",value = "文件id")
    @GetMapping(value = "getDocxToPdfAndGz")
    public HttpResult<?> getDocxToPdfAndGz(@RequestParam(value = "id",defaultValue = "") String id){
        /*if (StringUtils.isBlank(id)){
            return HttpResult.error("文件参数为空！");
        }

        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在！");
        }
        if (StringUtils.isNotBlank(wjjl.getFwjlx()) && wjjl.getFwjlx().equals(".pdf")){
            return HttpResult.error("当前文件已经是pdf无法再次生成，请重新编辑文档");
        }

        // 关闭文档
        Result closeResult1 = webOfficeFIle.closeFile(id);
        if (!closeResult1.isSuccess()){
            return HttpResult.error(closeResult1.getMessage());
        }

        // 将在线文档转pdf
        Result result = webOfficeFIle.getDocxToPdfFile(wjjl, wjjl.getFcflj());
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }

        HttpResult<?> httpResult = hnCaUtils.fileCaByGJZ(id);// 盖章
        if (!httpResult.isSuccess()){
            return HttpResult.error(httpResult.getMessage());
        }*/

        // 关闭文档
        return HttpResult.ok("服务不可用！");
    }

    @Log(title = "申请事项-将word文件关闭并保存")
    @ApiOperation(value = "申请事项-将word文件关闭并保存")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id",value = "文件id",required = true),
            @ApiImplicitParam(name = "isClose",value = "是否关闭文档，true=【关闭】")
    })
    @GetMapping(value = "getWebOfficeDownloadFile")
    public HttpResult<?> getWebOfficeDownloadFile(@RequestParam(value = "id",defaultValue = "") String id,
                                                  @RequestParam(value = "isClose",defaultValue = "false") boolean isClose){
        /*if (StringUtils.isBlank(id)){
            return HttpResult.error("文件参数为空！");
        }

        boolean isDel = false;
        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }
        if (StringUtils.isNotBlank(wjjl.getFwjlx()) && wjjl.getFwjlx().equals(".pdf")){
            return HttpResult.ok("保存关闭成功");
        }

        // 关闭文档
        Result closeResult1 = webOfficeFIle.closeFile(id);
        if (!closeResult1.isSuccess()){
            return HttpResult.error(closeResult1.getMessage());
        }

        webOfficeFIle.getWebOfficeDownloadFile2(wjjl, wjjl.getFcflj(), isDel);

        // 关闭文档
        if (isClose) {
            return HttpResult.ok("保存关闭成功");
        }else {

            return HttpResult.ok("保存成功");
        }*/

        return HttpResult.ok("服务不可用！");
    }

    @ApiOperation(value = "申请事项-打开在线文档")
    @ApiImplicitParam(name = "id",value = "文件id")
    @GetMapping(value = "openFile")
    public HttpResult<?> openFile(@RequestParam(value = "id",defaultValue = "") String id){
        /*if (StringUtils.isBlank(id)){
            return HttpResult.error("文件参数为空！");
        }

        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }
        if (StringUtils.isBlank(wjjl.getFwjlx())){
            return HttpResult.error("文件类型出错！");
        }
        if (!wjjl.getFwjlx().equals(".doc") && !wjjl.getFwjlx().equals(".docx")){
            return HttpResult.error("操作失败，只有文档才能打开！");
        }
        String url = webOfficeFIle.openFile(wjjl,wjjl.getId(),wjjl.getFcflj(),2,0);*/
        Map resultMap = new HashMap();
        resultMap.put("wordUrl", "");
        return HttpResult.ok(resultMap);
    }

    @ApiOperation(value = "申请事项-打开在线文档-只读模式")
    @ApiImplicitParam(name = "id",value = "文件id")
    @GetMapping(value = "openFileReadOnly")
    public HttpResult openFileReadOnly(@RequestParam(value = "id",defaultValue = "") String id){
        /*if (StringUtils.isBlank(id)){
            return HttpResult.error("文件参数为空！");
        }

        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }
        if (StringUtils.isBlank(wjjl.getFwjlx())){
            return HttpResult.error("文件类型出错！");
        }
        if (!wjjl.getFwjlx().equals(".doc") && !wjjl.getFwjlx().equals(".docx")){
            return HttpResult.error("操作失败，只有文档才能打开！");
        }
        String url = webOfficeFIle.openFile(wjjl,wjjl.getId(),wjjl.getFcflj(),2,1);*/
        Map resultMap = new HashMap();
        resultMap.put("wordUrl", "");
        return HttpResult.ok(resultMap);
    }

    @ApiOperation(value = "获取APP-申请事项-打开在线文档-只读模式")
    @ApiImplicitParam(name = "id",value = "文件id")
    @GetMapping(value = "openAppReadOnly")
    public HttpResult openAppReadOnly(@RequestParam(value = "id",defaultValue = "") String id){
        /*if (StringUtils.isBlank(id)){
            return HttpResult.error("文件参数为空！");
        }

        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }
        if (StringUtils.isBlank(wjjl.getFwjlx())){
            return HttpResult.error("文件类型出错！");
        }
        if (!wjjl.getFwjlx().equals(".doc") && !wjjl.getFwjlx().equals(".docx")){
            return HttpResult.error("操作失败，只有文档才能打开！");
        }
        String url = webOfficeFIle.openAppFile(wjjl,wjjl.getId(),wjjl.getFcflj(),2,1);*/
        Map resultMap = new HashMap();
        resultMap.put("wordUrl", "");
        return HttpResult.ok(resultMap);
    }

    @ApiOperation(value = "通用文件-打开在线文档-只读模式")
    @GetMapping(value = "openCommonZdwj")
    public HttpResult openCommonZdwj(@RequestParam(value = "id",defaultValue = "") String id){
       /* if (StringUtils.isBlank(id)){
            return HttpResult.error("文件参数为空！");
        }

        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }
        if (StringUtils.isBlank(wjjl.getFwjlx())){
            return HttpResult.error("文件类型出错！");
        }
        if (!wjjl.getFwjlx().equals(".doc") && !wjjl.getFwjlx().equals(".docx")){
            return HttpResult.error("操作失败，只有文档才能打开！");
        }

        String url = webOfficeFIle.openFile(wjjl,wjjl.getId(),wjjl.getFcflj(),2,1, false, false);*/
        Map resultMap = new HashMap();
        resultMap.put("wordUrl", "");
        return HttpResult.ok(resultMap);
    }

    @ApiOperation(value = "通用文件-企业申请材料-只读模式")
    @GetMapping(value = "openQyFile")
    public HttpResult openQyFile(@RequestParam(value = "id",defaultValue = "") String id){
        /*if (StringUtils.isBlank(id)){
            return HttpResult.error("文件参数为空！");
        }

        SpcySqsxQywjcl wjjl = spcySqsxQywjclService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }

        if (!Util.getWjHz(wjjl.getFclmc()).equals(".doc")
                && !Util.getWjHz(wjjl.getFclmc()).equals(".docx")){
            Map resultMap = new HashMap();
            resultMap.put("wordUrl", "");
            return HttpResult.ok(resultMap);
        }

        String url = webOfficeFIle.openQyFile(wjjl, wjjl.getId(), wjjl.getFcllj(),2,1);*/
        Map resultMap = new HashMap();
        resultMap.put("wordUrl", "");
        return HttpResult.ok(resultMap);
    }

    @ApiOperation(value = "获取APP-企业申请材料-只读模式")
    @GetMapping(value = "openAppQyFile")
    public HttpResult openAppQyFile(@RequestParam(value = "id",defaultValue = "") String id){
        /*if (StringUtils.isBlank(id)){
            return HttpResult.error("文件参数为空！");
        }

        SpcySqsxQywjcl wjjl = spcySqsxQywjclService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }

        if (!Util.getWjHz(wjjl.getFclmc()).equals(".doc")
                && !Util.getWjHz(wjjl.getFclmc()).equals(".docx")){
            Map resultMap = new HashMap();
            resultMap.put("wordUrl", "");
            return HttpResult.ok(resultMap);
        }

        String url = webOfficeFIle.openQyFile(wjjl, wjjl.getId(), wjjl.getFcllj(),2,1, true);*/
        Map resultMap = new HashMap();
        resultMap.put("wordUrl", "");
        return HttpResult.ok(resultMap);
    }

    @Log(title = "删除在线文档")
    @ApiOperation(value = "删除在线文档")
    @ApiImplicitParam(name = "id",value = "文件id")
    @GetMapping(value = "deleteFile")
    public HttpResult<?> deleteFile(String id){
        /*SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }
        webOfficeFIle.deleteFile(wjjl.getFcflj());
        return HttpResult.ok("删除成功");*/
        return HttpResult.ok("服务不可用！");
    }

    @Log(title = "申请事项-重新编辑Pdf文档")
    @ApiOperation(value = "重新编辑Pdf文档")
    @ApiImplicitParam(name = "id",value = "文件id")
    @GetMapping(value = "againEditPdfOnlineFile")
    public HttpResult<?> againEditPdfOnlineFile(@RequestParam(value = "id",defaultValue = "") String id){
        /*if (StringUtils.isBlank(id)){
            return HttpResult.error("文件参数不能为空");
        }

        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件记录不存在");
        }

        if (StringUtils.isNotBlank(wjjl.getFwjlx4()) && wjjl.getFwjlx4().equals(SpcyCommonConstant.SQSX_WJJL_TYPE4_SDSC)){
            return HttpResult.error("手动上传的文件不能重新编辑！");
        }

        SpcySqsxWjjl newWjjl = webOfficeFIle.againEditPdfOnlineFile(wjjl);// 修改文件
        if (newWjjl != null){
            String url = webOfficeFIle.openFile(newWjjl,newWjjl.getId(),newWjjl.getFcflj(),2,0);
            Map resultMap = new HashMap();
            resultMap.put("wordUrl",url);
            return HttpResult.ok(resultMap);
        }else {
            return HttpResult.error("重新编辑失败，当前文件不符合操作类型！");
        }*/

        return HttpResult.ok("服务不可用！");
    }



    @ApiOperation(value = "用户在线编辑类型切换")
    @ApiImplicitParam(name = "ftype",value = "在线编辑模式（包含分为[客户端模式]、[服务端模式]、默认为【客户端模式】）")
    @GetMapping(value = "onlineTypeSwitch")
    public HttpResult onlineTypeSwitch(@RequestParam(value = "ftype",defaultValue = "")String ftype){
        ftype = StringUtils.isNotBlank(ftype) ? ftype : "服务端模式";
        return HttpResultVo.HttpResultSave(ftype);
    }

    /** 废弃 */
    public HttpResult onlineTypeSwitchOld(@RequestParam(value = "ftype",defaultValue = "")String ftype){
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return HttpResult.error("登录已失效，请重新登录");
        }

        String userid = currentUser.getId();
        HttpResult httpResult = new HttpResult();

        List<SpcyRsOnlineEdit> userList = spcyRsOnlineEditService.list(new LambdaQueryWrapper<SpcyRsOnlineEdit>()
                .eq(StringUtils.isNotBlank(userid), SpcyRsOnlineEdit::getFuserid, userid));

        SpcyRsOnlineEdit oldOnlineEdit = null;
        String oldType = "";
        if (CollectionUtils.isNotEmpty(userList)){
            oldOnlineEdit = userList.get(0);
            oldType = oldOnlineEdit.getFtype();

            if (StringUtils.isNotBlank(ftype) && StringUtils.isNotBlank(oldType) && !ftype.equals(oldType)) {
                oldOnlineEdit.setFtype(ftype);
                spcyRsOnlineEditService.updateById(oldOnlineEdit);
            }

            if (StringUtils.isBlank(ftype)){
                httpResult.setResult(oldType);

                StringBuffer msg = new StringBuffer("初始化成功，当前在线编辑模式");
                msg.append("为[").append(oldType).append("]");
                httpResult.setMessage(msg.toString());
            }else {
                if (ftype.equals(oldType)){
                    httpResult.setResult(oldType);

                    StringBuffer msg = new StringBuffer("初始化成功，当前在线编辑模式");
                    msg.append("为[").append(oldType).append("]");
                    httpResult.setMessage(msg.toString());
                }else {
                    httpResult.setResult(ftype);

                    StringBuffer msg = new StringBuffer("切换成功，将在线编辑模式");
                    msg.append("从[").append(oldType).append("]切换为").append("[").append(ftype).append("]");
                    httpResult.setMessage(msg.toString());
                }
            }

        }else {
            if (StringUtils.isBlank(ftype)){
                ftype = "客户端模式";
            }
            SpcyRsOnlineEdit onlineEdit = new SpcyRsOnlineEdit();
            onlineEdit.setId(GetUuIdUtils.ReplaceUuId());
            onlineEdit.setFtype(ftype);
            onlineEdit.setFuserid(userid);
            spcyRsOnlineEditService.save(onlineEdit);

            StringBuffer msg = new StringBuffer("初始化成功，将在线编辑模式");
            msg.append("初始化为[").append(ftype).append("]");
            httpResult.setMessage(msg.toString());
            httpResult.setResult(ftype);
        }
        httpResult.setSuccess(true);
        return httpResult;
    }


    //    @AutoLog(value = "将本地文件上传到在线文档")
//    @ApiOperation(value = "将本地文件上传到在线文档")
//    @ApiImplicitParam(name = "id",value = "文件id")
//    @GetMapping(value = "WebOfficeUploadFile")
    public HttpResult<?> WebOfficeUploadFile(String id){
        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }
        Result result = webOfficeFIle.uploadWebOfficeFile(wjjl,wjjl.getFwjccmc(), wjjl.getFcflj());
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }
        return HttpResult.ok("上传成功");
    }

    //    @AutoLog(value = "判断在线文档是否已经打开")
//    @ApiOperation(value = "判断在线文档是否已经打开")
//    @ApiImplicitParam(name = "id",value = "文件id")
//    @GetMapping(value = "isOpenFile")
    public HttpResult<?> isOpenFile(String id){
        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }
        boolean openFile = webOfficeFIle.isOpenFile(wjjl.getId());
        if (openFile){
            return HttpResult.error("文档已打开");
        }
        return HttpResult.ok("文档未打开");
    }

    //    @AutoLog(value = "关闭在线文档")
//    @ApiOperation(value = "关闭在线文档")
//    @ApiImplicitParam(name = "id",value = "文件id")
//    @GetMapping(value = "closeFile")
    public HttpResult<?> closeFile(String id){
        SpcySqsxWjjl wjjl = spcySqsxWjjlService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件不存在");
        }
        Result result = webOfficeFIle.closeFile(wjjl.getId());
        if (!result.isSuccess()){
            return HttpResult.error(result.getMessage());
        }
        return HttpResult.ok("关闭成功");
    }
}
